import java.util.concurrent.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-09-09
 * Time: 22:08
 */
public class demo2 {
    public static void main(String[] args) {
        int corePoolSize = 5;
        int maximumSize = 10;
        int keepAlive = 5;
        BlockingQueue<Runnable> blockingQueue = new ArrayBlockingQueue<>(10);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler ignoreLatesTaskPolicy = new RejectedExecutionHandler() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                // 当触发拒绝策略时，直接“忽略”最新提交的任务（不做任何处理）
                System.out.println("最新任务 " + r + " 被忽略（线程池已达承载上限）");
            }
        };
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                corePoolSize,
                maximumSize,
                keepAlive,
                TimeUnit.SECONDS,
                blockingQueue,
                threadFactory,
                ignoreLatesTaskPolicy
        );
        // 提交 15 个任务（核心线程5 + 队列10 + 非核心线程5 = 最大承载20，剩余5个任务会触发拒绝）
        for (int i = 0; i < 25; i++) {
            final int taskId = i;
            threadPoolExecutor.submit(() -> {
                System.out.println("任务 " + taskId + " 正在执行，线程：" + Thread.currentThread().getName());
                try {
                    Thread.sleep(1000); // 模拟任务执行耗时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }

        // 关闭线程池（实际业务中按需关闭）
        threadPoolExecutor.shutdown();
    }
}
